<template>
  <div>
    <BasicTable @register="registerTable" @resize-column="handleResizeColumn">
      <template #toolbar>
        <a-button type="primary" @click="handleSearchTableCondition"> 条件 </a-button>
        <a-button type="primary" @click="handleSearchTableSearchModal"> 搜索 </a-button>
        <a-button type="primary" @click="handleExport"> 导出 </a-button>
        <a-button type="primary" @click="handleReset"> 重置列 </a-button>
      </template>
      <template
        #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
      >
        <div style="padding: 8px" v-if="pageColProps && pageColProps.length">
          <div class="text-right">
            <a-button type="link" @click="handleSubmitColsDebounce">保存</a-button>
          </div>
          <Divider style="margin: 5px 0" />
          <div style="height: 300px">
            <Scrollbar>
              <draggable
                v-model="pageColProps"
                :component-data="{
                  type: 'transition-group',
                }"
                :animation="180"
                handle=".draggable-move"
              >
                <template #item="{ element, index }">
                  <div class="mb-2">
                    <DragOutlined class="draggable-move mr-2 cursor-move" />
                    <Checkbox
                      v-model:checked="element.hide"
                      @change="handleChangeColProps($event, index)"
                    >
                      <Tooltip :title="element.display">
                        {{ element.display }}
                      </Tooltip>
                    </Checkbox>
                  </div>
                </template>
              </draggable>
            </Scrollbar>
          </div>
        </div>
      </template>
      <template #customFilterIcon="{ filtered }">
        <caret-down-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
      </template>
      <template #summary v-if="sumData && Object.keys(sumData).length">
        <TableSummary fixed>
          <TableSummaryRow>
            <TableSummaryCell :index="0">合计</TableSummaryCell>
            <TableSummaryCell
              :index="1"
              v-for="(item, index) in colProps"
              :key="`TableSummaryCell${index}`"
              class="text-center"
            >
              <template v-if="getSumField(item.dataIndex)">
                {{ sumData[item.dataIndex] }}
              </template>
            </TableSummaryCell>
          </TableSummaryRow>
        </TableSummary>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:info-standard-line',
              tooltip: '查看',
              onClick: handleView.bind(null, record),
              ifShow: () => !isEmpty(record.cws_op),
            },
          ]"
        />
      </template>
    </BasicTable>
    <SearchTableCondition
      @register="registerModalSearchTableCondition"
      @success="handleSuccessSearchTableCondition"
    />
    <SearchTableSearchModal
      @register="registerModalSearchTableSearchModal"
      @success="handleSuccessSearchTableSearchModal"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, unref, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { CaretDownOutlined, DragOutlined } from '@ant-design/icons-vue';
  import { Checkbox, Divider, Tooltip } from 'ant-design-vue';
  import { columns, searchFormSchema } from './searchTable.data';
  import {
    getQueryListQueryResultPageByScript,
    getQueryListQueryResultByScript,
    getQueryModifyColProps,
    getQueryResetCol,
    getQueryExportByScript,
  } from '/@/api/reportForms/reportForms';
  import { useRouter } from 'vue-router';
  import SearchTableCondition from './searchTableCondition.vue';
  import SearchTableSearchModal from './searchTableSearchModal.vue';
  import { isArray, isEmpty } from '/@/utils/is';
  import { useGo } from '/@/hooks/web/usePage';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDebounceFn } from '@vueuse/core';
  import { Scrollbar } from '/@/components/Scrollbar';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { downloadByData } from '/@/utils/file/download';
  import draggable from 'vuedraggable';

  export default defineComponent({
    name: 'SearchTable',
    components: {
      BasicTable,
      TableAction,
      CaretDownOutlined,
      SearchTableCondition,
      SearchTableSearchModal,
      Checkbox,
      Scrollbar,
      Divider,
      draggable,
      DragOutlined,
      Tooltip,
    },
    props: {
      activeRecord: {
        type: Object as PropType<Recordable>,
        default: {},
      },
    },
    setup(props, { emit }) {
      const { setTitle } = useTabs();
      const { createMessage } = useMessage();
      const sumData: any = ref({});
      const otherParams = ref<Recordable>({});
      const { currentRoute } = useRouter();
      const [registerTable, { reload, setLoading, setColumns, setProps }] = useTable({
        title: '',
        api: getQueryListQueryResultByScript,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        searchInfo: {
          // op: 'query',
        }, //额外的参数
        tableSetting: {
          setting: false,
        },
        beforeFetch: (info) => {
          info.id = currentRoute.value.query.id;
          if (!info.id) {
            info.id = props.activeRecord.queryId;
            info.mode = 'changeCondValue';
            info[props.activeRecord.destFieldName] = props.activeRecord.destFieldValue;
          }
          console.log('props.activeRecord', props.activeRecord);
          if (isEmpty(otherParams.value)) {
            info.moduleId = -1;
          } else {
            info = {
              ...info,
              ...otherParams.value,
            };
          }
          return info;
        },
        useSearchForm: false,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        // actionColumn: {
        //   width: 80,
        //   title: '操作',
        //   dataIndex: 'action',
        //   slots: { customRender: 'action' },
        //   fixed: undefined,
        // },
        afterFetch: async (data) => {
          data = data || [];
          let sumRow: Recordable = data[data.length - 1];
          if (Reflect.has(sumRow, '_row')) {
            sumData.value = sumRow;
            data.splice(data.length - 1);
          }
        },
      });

      function handleSuccess() {
        reload();
      }
      const colProps = ref<Recordable[]>([]);
      const pageColProps = ref<Recordable[]>([]);
      const fetch = (queryId = -1) => {
        const title = currentRoute.value.query.title;
        if (title) {
          setTitle(`${title}`);
        }
        if (!currentRoute.value.query.id && queryId === -1) {
          return;
        }

        if (queryId == -1) {
          queryId = currentRoute.value.query.id;
        }

        colProps.value = [];
        getQueryListQueryResultPageByScript({ id: queryId }).then((res) => {
          if (isArray(res.colProps)) {
            pageColProps.value = cloneDeep(res.colProps);
            pageColProps.value.forEach((item) => {
              item.hide = !item.hide;
            });
            const data = res.colProps.filter((item) => !item.hide && item.display != '操作');
            data.forEach((item) => {
              colProps.value.push({
                title: item.display,
                dataIndex: item.name,
                customFilterDropdown: true,
                width: item.width,
                align: item.align,
                ellipsis: true,
                resizable: item.sortable,
              });
            });
            setColumns(colProps.value);

            if (res.colProps.some((item) => item.display == '操作' && !item.hide)) {
              setProps({
                actionColumn: {
                  width: res.colProps.find((item) => item.display == '操作').width,
                  title: '操作',
                  dataIndex: 'action',
                  slots: { customRender: 'action' },
                  fixed: undefined,
                },
              });
            } else {
              setProps({ actionColumn: undefined });
            }
          }
        });
      };
      onMounted(fetch);

      //改变列
      const handleChangeColProps = (e, index) => {
        pageColProps.value[index].hide = e.target.checked;
      };

      const handleSubmitCols = async () => {
        try {
          const colProps = pageColProps.value.map((item) => {
            item.hide = !item.hide;
            return item;
          });
          const params = {
            op: 'modifyColProps',
            colProps: JSON.stringify(colProps),
            id: currentRoute.value.query.id,
          };
          setLoading(true);
          pageColProps.value = [];
          await getQueryModifyColProps(params);
          fetch();
          createMessage.success('操作成功');
        } catch (error) {
        } finally {
          setLoading(false);
        }
      };

      const handleResizeColumn = (w, col) => {
        col.width = w;
        const currentIndex = pageColProps.value.findIndex((item) => item.name === col.dataIndex);
        pageColProps.value[currentIndex].width = parseInt(w);
        handleSubmitColsDebounce();
      };
      // 防抖，延迟500ms执行
      const handleSubmitColsDebounce = useDebounceFn(handleSubmitCols, 500);

      //条件
      const [registerModalSearchTableCondition, { openModal: OpenModalSearchTableCondition }] =
        useModal();
      const handleSearchTableCondition = () => {
        OpenModalSearchTableCondition(true, {
          id: currentRoute.value.query.id,
        });
      };
      const handleSuccessSearchTableCondition = (params) => {
        otherParams.value = { op: 'query', ...params };
        reload();
      };

      //搜索
      const [registerModalSearchTableSearchModal, { openModal: OpenModalSearchTableSearchModal }] =
        useModal();
      const handleSearchTableSearchModal = () => {
        OpenModalSearchTableSearchModal(true, {
          id: currentRoute.value.query.id,
        });
      };
      const handleSuccessSearchTableSearchModal = (params) => {
        otherParams.value = { mode: 'filter', action: 'searchInResult', ...params };
        reload();
      };
      const go = useGo();
      //查看
      function handleView(record: Recordable) {
        go({
          path: '/smartModuleAddEditView',
          query: {
            isTab: true,
            isUpdate: 3,
            parentPath: unref(currentRoute).path,
            moduleCode: record.cws_op.moduleCode,
            id: record.cws_op['id'],
            formCode: record.cws_op.formCode,
            treeNodeCode: '',
            isTreeView: false,
            titleName: `详情-${record.cws_op.formName}`,
            cacheName: `smartModuleAddEditViewDetail${record.cws_op['id']}`,
          },
        });
      }
      const getSumField = (dataIndex) => {
        return Reflect.has(sumData.value, dataIndex);
      };

      //重置列
      const handleReset = async () => {
        try {
          setLoading(true);
          await getQueryResetCol({ id: currentRoute.value.query.id });
          pageColProps.value = [];
          fetch();
        } catch (error) {
        } finally {
          setLoading(false);
        }
      };
      const handleExport = async () => {
        try {
          setLoading(true);
          const data = await getQueryExportByScript({ id: currentRoute.value.query.id });
          if (data) {
            downloadByData(
              data,
              `${currentRoute.value.query.title || currentRoute.value.meta.title}.xls`,
            );
          }
        } catch (error) {
        } finally {
          setLoading(false);
        }
      };

      watch(
        () => props.activeRecord,
        (newVal) => {
          console.log('props.activeRecord', newVal);
          fetch(newVal.queryId);
        },
        {
          immediate: true,
        },
      );

      return {
        registerTable,
        handleSuccess,
        handleResizeColumn,
        registerModalSearchTableCondition,
        handleSuccessSearchTableCondition,
        handleSearchTableCondition,
        registerModalSearchTableSearchModal,
        handleSuccessSearchTableSearchModal,
        handleSearchTableSearchModal,
        handleView,
        colProps,
        isEmpty,
        sumData,
        getSumField,
        pageColProps,
        handleChangeColProps,
        handleReset,
        handleExport,
        handleSubmitColsDebounce,
      };
    },
  });
</script>
